package org.budo.poi.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.budo.support.freemarker.FreemarkerUtil;
import org.budo.support.lang.util.ListUtil;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.spring.expression.util.SpelUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class SheetUtil {
    public static void writeSheet(Sheet sheet, Map<String, String> columns, List<?> list) {
        writeSheet(sheet, columns, list, RowAppender.NONE);
    }

    public static void writeSheet(Sheet sheet, List<?> list, RowAppender rowAppender) {
        writeSheet(sheet, null, list, rowAppender);
    }

    public static void writeSheet(Sheet sheet, Map<String, String> columns, List<?> list, RowAppender rowAppender) {
        log.info("#32 writeSheet, sheet=" + sheet + ", columns=" + columns + ", list.size=" + ListUtil.size(list) + ", rowAppender=" + rowAppender);

        if (null == columns) {
            columns = new HashMap<String, String>(); // 没有固定列，都通过 rowAppender 写
        }

        Set<Entry<String, String>> entrySet = columns.entrySet();
        Entry<String, String>[] columnsEntries = entrySet.toArray(new Entry[entrySet.size()]);
        int columnCount = columnsEntries.length;

        // 第一行 标题行
        Row titleRow = sheet.createRow(0);
        for (int i = 0; i < columnCount; i++) {
            String title = columnsEntries[i].getKey();

            titleRow.createCell(i).setCellValue(title);
        }

        // 每一行内容
        for (int j = 0; j < list.size(); j++) {
            Row row = sheet.createRow(j + 1);
            Object each = list.get(j);

            for (int k = 0; k < columnCount; k++) {
                Map<String, Object> map = MapUtil.stringObjectMap("_index", k, "_each", each);
                String template = columnsEntries[k].getValue();

                String value = merge(template, map);

                Cell cell = row.createCell(k);
                CellUtil.setCellValue(cell, value);
            }

            rowAppender.appendRow(each, row);
        }

        // 加 title
        rowAppender.appendTitle(titleRow);
    }

    private static String merge(String template, Map<String, Object> map) {
        if (template.startsWith("#{") && template.endsWith("}")) {
            return SpelUtil.merge(template, map);
        }

        return FreemarkerUtil.freemarkerRender(template, map);
    }
}